package api.cie.rss.adapters;

import java.util.List;

import android.content.Context;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import api.cie.rss.R;
import api.cie.rss.common.Category;

public class CategoryAdapter extends BaseAdapter {
	
    private List<Category> listCategory;
	private Context context;
	private LayoutInflater inflater;
	
	public CategoryAdapter (Context context, List<Category> listCategory){
		this.context = context;
		this.listCategory = listCategory;
		inflater = LayoutInflater.from(context);
	}

	@Override
	public int getCount() {
		return listCategory.size();
	}

	@Override
	public Object getItem(int position) {
		return listCategory.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		convertView =  inflater.inflate(R.layout.category_row, parent, false);
		EditText titleCat = (EditText)convertView.findViewById(R.id.titleCategorie);
		titleCat.setText(listCategory.get(position).getTitle());
		
		CheckBox active = (CheckBox)convertView.findViewById(R.id.activeCat);
		active.setTag(position);
		active.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Integer p = (Integer)v.getTag();
				if(((CheckBox)v).isChecked()){
					listCategory.get(p).ischecked = true;
				}
				else{
					listCategory.get(p).ischecked = false;
				}
			}
		});
		
		titleCat.setTag(position);
		titleCat.setOnKeyListener(new OnKeyListener() {
			
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				Integer p = (Integer)v.getTag();
				listCategory.get(p).setTitle(String.valueOf(((EditText)v).getText()));
				return false;
			}
		});
		
		return convertView;
	}

}
